
package com.example.binpacking.interceptor;

import com.example.binpacking.service.InterviewerService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    InterviewerService interviewerService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        // 排除 Swagger 相关的请求
        if (uri.startsWith("/swagger") || uri.startsWith("/v2/api-docs") || uri.startsWith("/webjars") || uri.startsWith("/swagger-resources")) {
            return true;
        }
        // 从请求头中获取Token
        String token = request.getHeader("token");
        // 检查Token是否为"123456"
        if (token == null) {
            response.setStatus(200);

            Map<String, Object> map = new HashMap<>();
            response.setContentType("application/json;charset=utf-8");
            //is null or token unavailable`
            map.put("msg", "n");
            map.put("code", 200);
            response.getWriter().write(new ObjectMapper().writeValueAsString(map));
            return false;
        }
        return true;
    }
}
